package com.gitee.shigen.oss.cloud;

import com.gitee.shigen.oss.config.CloudStorageConfig;
import com.gitee.shigen.oss.config.CloudStorageConfig.MinioProperties;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * MINIO存储实现
 *
 * @author shigenfu
 * @date 2024/12/9 22:15
 */
public class MinioStorageService extends CloudStorageService {

    private MinioClient client;

    public MinioStorageService(CloudStorageConfig config) {
        this.config = config;

        init();
    }

    private void init() {
        MinioProperties properties = this.config.getMinio();

        this.client = MinioClient.builder().endpoint(properties.getEndpoint()).credentials(properties.getAccessKey(), properties.getSecretKey()).build();
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(null, suffix));
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            PutObjectArgs uploadObjectArgs = PutObjectArgs.builder()
                .bucket(config.getMinio().getBucketName())
                .stream(inputStream, inputStream.available(), -1)
                .object(path)
                .build();

            ObjectWriteResponse objectWriteResponse = client.putObject(uploadObjectArgs);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return config.getMinio().getEndpoint() + "/" + config.getMinio().getBucketName() + "/" + path;
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return null;
    }
}
